package com.hugh.commom.zk.client;

import com.hugh.commom.util.NetworkUtils;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.ExistsBuilderMain;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.AbstractFactoryBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: Hugh
 * @Date: 2020/6/22
 */
@Component("zookeeperRegistryFactory")
public class ZookeeperRegistryFactory implements FactoryBean {

    private static CuratorFramework client;

    @Override
    public Object getObject() throws Exception {
        return getZkClient();
    }

    @Override
    public Class<?> getObjectType() {
        return CuratorFramework.class;
    }

    //注册的zk路径 /rpc/org.apache.dubbo.demo.DemoService/providers/ip
    //key: org.apache.dubbo.demo.DemoService , val: ip
    private   CuratorFramework getZkClient(){
        if(Objects.isNull(client)) {
            RetryPolicy exponentialBackoffRetry = new ExponentialBackoffRetry(1000, 3);

            client = CuratorFrameworkFactory.builder()
                    .connectString("127.0.0.1:2181")
                    .sessionTimeoutMs(50000)
                    .connectionTimeoutMs(30000)
                    .retryPolicy(exponentialBackoffRetry)
                    // 独立的命名空间 /base
                    .namespace("rpc")
                    .build();
        }
        client.start();
        return client;
    }
}
